<template>
  <PageWrapper
    dense
    contentFullHeight
    fixedHeight
    contentClass="flex"
    v-loading="getLoading"
    loading-tip="加载中，请稍后..."
  >
    <!-- <DeptTree class="w-1/4 xl:w-1/5" @select="handleSelect" /> -->
    <!-- <BasicTable @register="registerTable" class="w-3/4 xl:w-4/5" :searchInfo="searchInfo"> -->
    <div class="acc-list-div">
      <BasicTable @register="registerTable" :searchInfo="searchInfo">
        <template #toolbar>
          <a-button type="primary" @click="handleExport">导出</a-button>
          <a-button type="primary" @click="handleCreate">重算</a-button>
        </template>
        <template #districtOne="{ record, column }">
          {{ getDistrictOne(record[column.dataIndex]) }}
        </template>
        <template #districtMany="{ record, column }">
          {{ getDistrictMany(record[column.dataIndex]) }}
        </template>
        <template #action="{ record }">
          <TableAction
            :actions="[
              // {
              //   icon: 'clarity:note-edit-line',
              //   tooltip: '编辑用户资料',
              //   onClick: handleEdit.bind(null, record),
              // },
              // {
              //   icon: 'ant-design:lock-outlined',
              //   tooltip: '修改密码',
              //   onClick: handleEditPwd.bind(null, record),
              // },
              // {
              //   icon: 'ant-design:delete-outlined',
              //   color: 'error',
              //   tooltip: '删除此用户',
              //   popConfirm: {
              //     title: '是否确认删除',
              //     confirm: handleDelete.bind(null, record),
              //   },
              // },
            ]"
          />
        </template>
      </BasicTable>
    </div>
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, reactive, ref } from 'vue';

  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { getFireStatList, reCountFireStatList } from '/@/api/demo/system';
  import { getFireStatListxls, reCountFireStatList2 } from '/@/api/demo/system';
  import { PageWrapper } from '/@/components/Page';
  import { useModal } from '/@/components/Modal';
  import {
    downloadByUrl,
    downloadByData,
    downloadByBase64,
    downloadByOnlineUrl,
  } from '/@/utils/file/download';
  import { useGlobSetting } from '/@/hooks/setting';
  const globSetting = useGlobSetting();
  import { columns, searchFormSchema } from './stat.data';
  import { useGo } from '/@/hooks/web/usePage';

  import { useUserStore } from '/@/store/modules/user';
  export default defineComponent({
    name: 'AccountManagement',
    components: { BasicTable, PageWrapper, TableAction },
    setup() {
      const go = useGo();

      const getLoading = ref(false);
      const userStore = useUserStore();
      const [registerModal, { openModal }] = useModal();
      const [registerModal2, { openModal: openModal2 }] = useModal();
      const searchInfo = reactive<Recordable>({});
      // 搜索条件
      const searchFormSchema1: any[] = [
        {
          label: '统计类型',
          field: 'type',
          model: 'model.type',
          component: 'RadioGroup',
          defaultValue: '0',
          componentProps: ({ schema, formModel }) => {
            return {
              options: [
                {
                  label: '全部',
                  value: '0',
                },
                {
                  label: '777村',
                  value: '777',
                },
                {
                  label: '107村',
                  value: '107',
                },
              ],
              onChange: function (checkedValue) {
                // console.log('@checkedValue--选中的值1111', checkedValue.target.value);
                let type = checkedValue.target.value;
                formModel.type = checkedValue.target.value;
                reload({ type });
              },
            };
          },
          labelWidth: '6em',
          colProps: { span: 6, flex: 1 },
        },
        // {
        //   field: 'create_on',
        //   label: '创建时间',
        //   component: 'RangePicker',
        //   colProps: {
        //     span: 6,
        //     flex: 1, // 独占一行
        //   },
        //   labelWidth: '6em',
        // },
        // {
        //   field: 'modified_on',
        //   label: '修改时间',
        //   component: 'RangePicker',
        //   colProps: {
        //     span: 6,
        //     flex: 1, // 独占一行
        //   },
        //   labelWidth: '6em',
        // },
      ];
      function getColumns() {
        const userStore = useUserStore();
        let userInfo = userStore?.getUserInfo;
        const { role } = userInfo;
        if (role === 'City') {
          console.log(' 市级');
          let column = columns.filter(
            (item) => item.dataIndex !== 'town' && item.dataIndex !== 'village',
          );
          return column;
        } else if (role === 'Area') {
          let column = columns.filter(
            (item) => item.dataIndex !== 'name' && item.dataIndex !== 'village',
          );
          return column;
        } else if (role === 'Street') {
          let column = columns.filter(
            (item) => item.dataIndex !== 'name' && item.dataIndex !== 'town',
          );
          return column;
        }
      }
      const [registerTable, { reload, getForm, updateTableDataRecord }] = useTable({
        title: '消防销账汇总',
        api: getFireStatList,
        rowKey: 'id',
        columns: getColumns(),
        pagination: { pageSize: 50 },
        formConfig: {
          schemas: searchFormSchema1,
          autoSubmitOnEnter: true,
        },
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        handleSearchInfoFn(info) {
          console.log('handleSearchInfoFn', info);
          return info;
        },
        // actionColumn: {
        //   width: 120,
        //   title: '操作',
        //   dataIndex: 'action',
        //   slots: { customRender: 'action' },
        // },
      });

      function handleCreate() {
        getLoading.value = true;
        reCountFireStatList({})
          .then((_) => {
            getLoading.value = false;
            reload();
          })
          .catch(() => {
            getLoading.value = false;
          });
      }

      function handleExport() {
        const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
        const tk = userStore.getToken;
        // console.log(tk);
        // const fv = getForm().getFieldsValue();
        // const searchParams = encodeData(fv);
        // console.log(searchParams);
        // downloadByUrl({
        //   url: `${uriBase}/houses/pcyh/ExportExcel?access_token=${tk}`,
        //   target: '_blank',
        // });
        // 获取查询条件的参数
        const searchParams: any = getForm().getFieldsValue();
        // console.log('@searchParams', searchParams.type);
        let type = searchParams.type;
        let url = `${uriBase}/houses/pcyh/ExportExcel?access_token=${tk}&type=${type}`;
        console.log('@url', url);

        downloadByUrl({
          url: url,
          target: '_blank',
        });
      }
      function toExcel() {
        // getLoading.value = true;
        // reCountFireStatList2({})
        //   .then((_) => {
        //     getLoading.value = false;
        //     reload();
        //   })
        //   .catch(() => {
        //     getLoading.value = false;
        //   });
      }

      function getDistrictOne(value) {
        if (value) {
          return value.regionName;
        }
        return value;
      }

      function getDistrictMany(value) {
        if (value) {
          const fds: string[] = [];
          value.forEach((element) => {
            fds.push(element.regionName);
          });

          if (fds.length > 0) {
            return fds.toString();
          }
        }

        return value;
      }

      function handleEdit(record: Recordable) {
        openModal(true, {
          record,
          isUpdate: true,
        });
      }

      function handleEditPwd(record: Recordable) {
        openModal2(true, {
          record,
          isUpdate: true,
        });
      }

      async function handleDelete(record: Recordable) {
        await delAccount(record);
        reload();
      }

      function handleSuccess({ isUpdate, values }) {
        if (isUpdate) {
          // 演示不刷新表格直接更新内部数据。
          // 注意：updateTableDataRecord要求表格的rowKey属性为string并且存在于每一行的record的keys中
          const result = updateTableDataRecord(values.id, values);
          console.log(result);
        } else {
          reload();
        }
      }

      function handleSelect(deptId = '') {
        searchInfo.departmentId = deptId;
        reload();
      }

      function handleView(record: Recordable) {
        go('/system/account_detail/' + record.id);
      }

      return {
        registerTable,
        registerModal,
        registerModal2,
        handleCreate,
        toExcel,
        handleExport,
        handleEdit,
        handleEditPwd,
        handleDelete,
        handleSuccess,
        handleSelect,
        handleView,
        searchInfo,
        getDistrictOne,
        getDistrictMany,
        getLoading,
      };
    },
  });
</script>
